package mp

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"
)

type ClassifyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewClassifyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassifyListLogic {
	return &ClassifyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ClassifyListLogic) ClassifyList() (resp []*types.ClassifyList, err error) {
	subDatas := []*models.Classify{}
	db.FindDatasAsc(&subDatas, xb.And(xb.Gt{"pid": 0}))
	subClassify := make(map[int][]*types.ClassifyList)
	for _, v := range subDatas {
		tmp := &types.ClassifyList{
			Id:       v.Id,
			Title:    v.Title,
			IsUse:    v.IsUse,
			Pid:      v.Pid,
			Children: []*types.ClassifyList{},
		}
		subClassify[v.Pid] = append(subClassify[v.Pid], tmp)
	}

	data := []*models.Classify{}
	db.FindDatasAsc(&data, xb.And(xb.Eq{"pid": 0}))
	resp = []*types.ClassifyList{}
	for _, v := range data {
		tmp := &types.ClassifyList{
			Id:    v.Id,
			Title: v.Title,
			IsUse: v.IsUse,
			Pid:   v.Pid,
		}
		if ost, ok := subClassify[v.Id]; ok {
			tmp.Children = ost
		}
		resp = append(resp, tmp)
	}

	return resp, nil
}
